package com.hjimi.ski.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Process;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

/**
 * Created by Administrator on 2019/4/17 0017.
 */

public class AppManager {

    private static Stack<Activity> sActivityStack;
    private static AppManager sInstance;

    private AppManager() {

    }

    public static AppManager getAppManager() {
        if (sInstance == null) {
            sInstance = new AppManager();
        }

        return sInstance;
    }

    public void addActivity(Activity activity) {
        if (sActivityStack == null) {
            sActivityStack = new Stack<Activity>();
        }
        sActivityStack.add(activity);
    }

    public void removeActivity(Activity activity) {
        try {
            if (activity != null) {
                sActivityStack.remove(activity);
                activity.finish();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void removeActivity(Class<?> cls) {
        try {
            for (Activity activity : sActivityStack) {
                try {
                    if (activity.getClass().equals(cls)) {
                        removeActivity(activity);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    public boolean isContainsActivity(Class<?> cls) {
        try {
            for (Activity activity : sActivityStack) {
                if (activity.getClass().equals(cls)) {
                    return true;
                }
            }
            return false;
        }catch (Exception e){
            return false;
        }
    }

    public void removeAllActivity() {
        for (int i = 0; i < sActivityStack.size(); ++i) {
            if (null != sActivityStack.get(i)) {
                ((Activity) sActivityStack.get(i)).finish();
            }
        }

        sActivityStack.clear();
    }

    @SuppressLint("MissingPermission")
    public void AppExit(Context context) {
        try {
            this.removeAllActivity();
            @SuppressLint("WrongConstant") ActivityManager activityMgr = (ActivityManager) context.getSystemService("activity");
            activityMgr.killBackgroundProcesses(context.getPackageName());
            System.exit(0);
        } catch (Exception var3) {
//            Logger.e(var3);
        }

    }

    @SuppressLint("MissingPermission")
    public static int gc(Context context) {
        long i = (long) getDeviceUsableMemory(context);
        int count = 0;
        @SuppressLint("WrongConstant") ActivityManager am = (ActivityManager) context.getSystemService("activity");
        List<ActivityManager.RunningServiceInfo> serviceList = am.getRunningServices(100);
        if (serviceList != null) {
            Iterator var6 = serviceList.iterator();

            while (var6.hasNext()) {
                ActivityManager.RunningServiceInfo service = (ActivityManager.RunningServiceInfo) var6.next();
                if (service.pid != Process.myPid()) {
                    try {
                        Process.killProcess(service.pid);
                        ++count;
                    } catch (Exception var16) {
                        var16.getStackTrace();
                    }
                }
            }
        }

        List<ActivityManager.RunningAppProcessInfo> processList = am.getRunningAppProcesses();
        if (processList != null) {
            Iterator var18 = processList.iterator();

            label46:
            while (true) {
                ActivityManager.RunningAppProcessInfo process;
                do {
                    if (!var18.hasNext()) {
                        break label46;
                    }

                    process = (ActivityManager.RunningAppProcessInfo) var18.next();
                } while (process.importance <= 200);

                String[] pkgList = process.pkgList;
                String[] var10 = pkgList;
                int var11 = pkgList.length;

                for (int var12 = 0; var12 < var11; ++var12) {
                    String pkgName = var10[var12];
//                    Logger.d("======正在杀死包名：" + pkgName);

                    try {
                        am.killBackgroundProcesses(pkgName);
                        ++count;
                    } catch (Exception var15) {
//                        Logger.e(var15);
                    }
                }
            }
        }

//        Logger.d("清理了" + ((long)getDeviceUsableMemory(context) - i) + "M内存");
        return count;
    }

    public static int getDeviceUsableMemory(Context context) {
        @SuppressLint("WrongConstant") ActivityManager am = (ActivityManager) context.getSystemService("activity");
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return (int) (mi.availMem / 1048576L);
    }

    public static List<PackageInfo> getAllApps(Context context) {
        List<PackageInfo> apps = new ArrayList();
        PackageManager pManager = context.getPackageManager();
        List<PackageInfo> paklist = pManager.getInstalledPackages(0);

        for (int i = 0; i < paklist.size(); ++i) {
            PackageInfo pak = (PackageInfo) paklist.get(i);
            if ((pak.applicationInfo.flags & 1) <= 0) {
                apps.add(pak);
            }
        }

        return apps;
    }

    public static boolean isBackground(Context context) {
        @SuppressLint("WrongConstant") ActivityManager am = (ActivityManager) context.getApplicationContext().getSystemService("activity");
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = ((ActivityManager.RunningTaskInfo) tasks.get(0)).topActivity;
            if (!topActivity.getPackageName().equals(context.getApplicationContext().getPackageName())) {
                return true;
            }
        }

        return false;
    }

    public static void copyToClipboard(Context context, String text) {
        @SuppressLint("WrongConstant") ClipboardManager cbm = (ClipboardManager) context.getApplicationContext().getSystemService("clipboard");
        cbm.setPrimaryClip(ClipData.newPlainText(context.getApplicationContext().getPackageName(), text));
    }

    @SuppressLint("WrongConstant")
    public static void closeInputMethod(Activity act) {
        View view = act.getCurrentFocus();
        if (view != null) {
            ((InputMethodManager) act.getApplicationContext().getSystemService("input_method")).hideSoftInputFromWindow(view.getWindowToken(), 2);
        }

    }
}